<template>
	<view>
		<view class="cu-chat" style="margin-bottom: 20px">
			<!-- <view v-if="!isHistory" style="margin-top: 5%;font-size: 14px;text-align: center;color: lightgrey"
				@tap="handleChangeView">查看历史会话</view> -->
			<!-- <scroll-view v-if="!isHistory" class="gradient" :class="theme" :scroll-y="true">
				<view class="gradient_radius">
					<view class="gradient_radius_text">您好</view>
					<view class="gradient_radius_text">桂鸟客服为您服务</view>
					<view class="gradient_radius_text_small">我可以帮您查订单、作业、支付等各类问题， 您想问点什么呢</view>
					<view class="gradient_item" v-for="(item, index) in questionList" :key="index"
						@click="questionClick(item)">
						<view style="width: 80%">
							{{item.question}}
						</view>
						<img style="width: 15px;height: 15px" :src="`${$hd.baseUrl}/images/icon-right.png`" alt="">
					</view>
				</view>

				<view class="chat-item" v-for="(item, index) in questionAnswerList" :key="index">
					<view v-if="item.senderId==1" class="cu-item self">
						<view class="main">
							<view style="word-break:break-all;" class="content shadow">
								{{ item.content }}
							</view>
						</view>
						<image class="cu-avatar round bg-white" v-if="avatar" :src=avatar mode="aspectFit"></image>
						<image class="cu-avatar round bg-white" v-else :src="`${$hd.baseUrl}/images/flyer.png`"
							mode="aspectFit"></image>
					</view>

					<view v-else class="cu-item">
						<view class="cu-avatar round bg-white"
							:style="{'background-image':`url(${$hd.baseUrl}/images/icon-inf-service.png)`}">
						</view>
						<view class="main">
							<view style="word-break:break-all;" class="content shadow">
								{{ item.content }}
							</view>
						</view>
					</view>
				</view>

			</scroll-view> -->
			<scroll-view class="scroll-view" :class="theme" :style="{height:scrollViewHeight+'px'}" :scroll-y="true"
				:scroll-top="scrollTop" :scroll-with-animation="true">
				<view v-if="chatListHis.length>0" id="scroll-view-content">
					<view class="chat-item" v-for="(item, index) in chatListHis" :key="index">
						<view v-if="item.senderId!==1" class="cu-item self">
							<!--文字-->
							<view class="main" v-if="item.contentType==='1'">
								<!-- <view class="action">
				  <text class="cuIcon-locationfill text-orange text-xxl"></text>
				</view> -->
								<view style="word-break:break-all;" class="content shadow">
									{{ item.content }}
								</view>
							</view>
							<!--图文-->
							<view class="main" v-if="item.contentType==='2'">
								<view class="content shadow"
									style="display: flex;flex-direction: column;align-items: flex-start;">
									<image :src="`${$hd.baseUrl}/common/file/${item.filesId}`" class="radius"
										mode="widthFix"></image>
									<view style="word-break:break-all;">
										{{ item.content }}
									</view>
								</view>
							</view>
							<!--视频-->
							<view class="main" v-if="item.contentType==='3'">
								<view class="content shadow"
									style="display: flex;flex-direction: column;align-items: flex-start;">
									<video style="width: 200px" :src="`${$hd.baseUrl}/common/file/${item.filesId}`"
										:controls="true" :autoplay="false" />
								</view>
							</view>
							<!--              <view class="cu-avatar round bg-white"-->
							<!--                    style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big107000.jpg);">-->
							<!--              </view>-->
							<image class="cu-avatar round bg-white" v-if="avatar" :src=avatar mode="aspectFit"></image>
							<image class="cu-avatar round bg-white" v-else :src="`${$hd.baseUrl}/images/flyer.png`"
								mode="aspectFit"></image>
							<view class="date">{{ item.createDate }}</view>
						</view>


						<view v-else class="cu-item">
							<view class="cu-avatar round bg-white"
								:style="{'background-image':`url(${$hd.baseUrl}/images/icon-inf-service-2.png)`}">
							</view>
							<!--文字-->
							<view class="main" v-if="item.contentType==='1'">
								<view style="word-break:break-all;" class="content shadow">
									{{ item.content }}
								</view>
							</view>
							<!--图文-->
							<view class="main" v-if="item.contentType==='2'">
								<view class="content shadow"
									style="display: flex;flex-direction: column;align-items: flex-start;">
									<image :src="`${$hd.baseUrl}/common/file/${item.filesId}`" class="radius"
										mode="widthFix"></image>
									<view style="word-break:break-all;">
										{{ item.content }}
									</view>
								</view>
							</view>
							<!--视频-->
							<view class="main" v-if="item.contentType==='3'">
								<view class="content shadow"
									style="display: flex;flex-direction: column;align-items: flex-start;">
									<video style="width: 200px" :src="`${$hd.baseUrl}/common/file/${item.filesId}`"
										:controls="true" :autoplay="false" />
								</view>
							</view>

							<view class="date">{{ item.createDate }}</view>
						</view>
					</view>
				</view>

				<view class="gradient">

					<view class="gradient_radius">
						<view class="gradient_radius_text">您好</view>
						<view class="gradient_radius_text">桂鸟客服为您服务</view>
						<view class="gradient_radius_text_small">我可以帮您查订单、作业、支付等各类问题， 您想问点什么呢</view>
						<view class="gradient_item" v-for="(item, index) in questionList" :key="index"
							@click="questionClick(item)">
							<view style="width: 80%">
								{{item.question}}
							</view>
							<img style="width: 15px;height: 15px" :src="`${$hd.baseUrl}/images/icon-right.png`" alt="">
						</view>
					</view>
				</view>
				<!-- 消息 -->
				<!-- <view class="chat-item" v-for="(item, index) in questionAnswerList" :key="index">
					<view v-if="item.senderId==1" class="cu-item self">
						<view class="main">
							<view style="word-break:break-all;" class="content shadow">
								{{ item.content }}
							</view>
						</view>
						<image class="cu-avatar round bg-white" v-if="avatar" :src=avatar mode="aspectFit"></image>
						<image class="cu-avatar round bg-white" v-else :src="`${$hd.baseUrl}/images/flyer.png`"
							mode="aspectFit"></image>
					</view>

					<view v-else class="cu-item">
						<view class="cu-avatar round bg-white"
							:style="{'background-image':`url(${$hd.baseUrl}/images/icon-inf-service.png)`}">
						</view>
						<view class="main">
							<view style="word-break:break-all;" class="content shadow">
								{{ item.content }}
							</view>
						</view>
					</view>
				</view> -->
				<view v-if="chatList.length>0" id="scroll-view-content">
					<view class="chat-item las" v-for="(item, index) in chatList" :key="index">
						<view v-if="item.senderId!==1" class="cu-item self">
							<!--文字-->
							<view class="main" v-if="item.contentType==='1'">
								<!-- <view class="action">
                  <text class="cuIcon-locationfill text-orange text-xxl"></text>
                </view> -->
								<view style="word-break:break-all;" class="content shadow">
									{{ item.content }}
								</view>
							</view>
							<!--图文-->
							<view class="main" v-if="item.contentType==='2'">
								<view class="content shadow"
									style="display: flex;flex-direction: column;align-items: flex-start;">
									<image :src="`${$hd.baseUrl}/common/file/${item.filesId}`" class="radius"
										mode="widthFix"></image>
									<view style="word-break:break-all;">
										{{ item.content }}
									</view>
								</view>
							</view>
							<!--视频-->
							<view class="main" v-if="item.contentType==='3'">
								<view class="content shadow"
									style="display: flex;flex-direction: column;align-items: flex-start;">
									<video style="width: 200px" :src="`${$hd.baseUrl}/common/file/${item.filesId}`"
										:controls="true" :autoplay="false" />
								</view>
							</view>
							<!--              <view class="cu-avatar round bg-white"-->
							<!--                    style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big107000.jpg);">-->
							<!--              </view>-->
							<image class="cu-avatar round bg-white" v-if="avatar" :src=avatar mode="aspectFit"></image>
							<image class="cu-avatar round bg-white" v-else :src="`${$hd.baseUrl}/images/flyer.png`"
								mode="aspectFit"></image>
							<view class="date">{{ item.createDate }}</view>
						</view>


						<view v-else class="cu-item">
							<view class="cu-avatar round bg-white"
								:style="{'background-image':`url(${$hd.baseUrl}/images/icon-inf-service-2.png)`}">
							</view>
							<!--文字-->
							<view class="main" v-if="item.contentType==='1'">
								<view style="word-break:break-all;" class="content shadow">
									{{ item.content }}
								</view>
							</view>
							<!--图文-->
							<view class="main" v-if="item.contentType==='2'">
								<view class="content shadow"
									style="display: flex;flex-direction: column;align-items: flex-start;">
									<image :src="`${$hd.baseUrl}/common/file/${item.filesId}`" class="radius"
										mode="widthFix"></image>
									<view style="word-break:break-all;">
										{{ item.content }}
									</view>
								</view>
							</view>
							<!--视频-->
							<view class="main" v-if="item.contentType==='3'">
								<view class="content shadow"
									style="display: flex;flex-direction: column;align-items: flex-start;">
									<video style="width: 200px" :src="`${$hd.baseUrl}/common/file/${item.filesId}`"
										:controls="true" :autoplay="false" />
								</view>
							</view>

							<view class="date">{{ item.createDate }}</view>
						</view>
					</view>
				</view>
				<view v-else style="margin-top: 5%;font-size: 14px;text-align: center;color: lightgrey">
					无更多聊天记录
				</view>
			</scroll-view>
		</view>

		<!-- 输入框 -->
		<view class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]">
			<!--			<view class="action">-->
			<!--				<text class="cuIcon-sound text-grey"></text>-->
			<!--			</view>-->
			<input v-model="content" class="solid-bottom" :adjust-position="false" :focus="false" maxlength="300"
				cursor-spacing="10" @focus="InputFocus" @blur="InputBlur" />
			<view class="action" @tap="showAdd" data-target="bottomModal">
				<text class="cuIcon-roundadd text-grey"></text>
			</view>
			<button class="cu-btn bg-blue shadow" @tap="sendAdmin()">发送</button>
		</view>
		<!--加载弹窗-->
		<view class="cu-load load-modal" v-if="loadModal">
			<!-- <view class="cuIcon-emojifill text-orange"></view> -->
			<view class="gray-text">加载中...</view>
		</view>

		<!--图片视频选择弹窗-->
		<view class="cu-modal bottom-modal" :class="modalName=='bottomModal'?'show':''">
			<view class="cu-dialog">
				<view style="width: 100%;height: 150px;background-color: white">
					<view @tap="chooseImg" class="dialog-item">上传图片</view>
					<view @tap="chooseVideo" class="dialog-item">上传视频</view>
					<view @tap="hideModal" class="dialog-item">取消</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	export default {
		computed: {
			...mapGetters(['theme'])
		},
		data() {
			return {
				InputBottom: 0,
				chatListHis: [],
				chatList: [],
				content: "",
				scrollTop: 0, //滚动条位置
				scrollViewHeight: 900, //滚动视图的高度,
				avatar: '',
				loadModal: false,
				modalName: '',
				gridCol: 3,
				gridBorder: false,
				filesId: '',
				questionList: [],
				questionAnswerList: []
			};
		},
		onShow() {
			this.getQueryList();
			this.look();
			if (this.theme == 'farmer') {
				uni.setNavigationBarColor({
					backgroundColor: '#0BCA89',
					frontColor: '#ffffff'
				});
			} else {
				uni.setNavigationBarColor({
					backgroundColor: '#006BFE',
					frontColor: '#ffffff',
				});
			}
		},
		methods: {
			questionClick(item) {
				// let aItem = {
				// 	content: item.question,
				// 	senderId: 1
				// }
				// let bItem = {
				// 	content: item.answer,
				// 	senderId: 2
				// }
				// this.questionAnswerList.push(aItem);
				// this.questionAnswerList.push(bItem);
				this.content = item.question
				this.sendAdmin(item.id)
			},
			getQueryList() {
				this.$http.get('cadre/question/list', {
					params: {
						pageNum: 1,
						pageSize: 100,
						total: 0,
						theme: this.theme
					}
				}).then(res => {
					console.log(res)
					this.questionList = res.rows
				})
			},
			async look() {
				uni.getSystemInfo({
					success: (res) => {
						//动态获取页面高度，减去底部输入框高度
						this.scrollViewHeight = res.windowHeight - uni.upx2px(120);
					}
				});
				this.loadModal = true;
				this.getWebsocket();
				await this.getHistory(1);
				//清除客服信息未读状态
				this.$http.get('/socketMsg/eliminateMessage', {
					params: {
						"flyerId": uni.getStorageSync('userInfo').user.id
					}
				}).then(res => {
					this.$store.commit("message/clear_customer_count")
					this.$store.dispatch("message/updateMessage")
				})
				this.avatar = this.$hd.baseUrl + '/common/file/' + uni.getStorageSync('userInfo').user.avatar
			},
			showAdd() {
				this.modalName = 'bottomModal';
			},
			hideModal() {
				this.modalName = null
			},
			scrollToBottom() {
				this.$nextTick(() => {
					// const query = uni.createSelectorQuery().in(this);
					// query
					//   .select("#id")
					//   .boundingClientRect((data) => {
					//     console.log("得到布局位置信息" + JSON.stringify(data));
					//     console.log("节点离页面顶部的距离为" + data.top);
					//   })
					//   .exec();
					uni.createSelectorQuery().in(this).select('#scroll-view-content').boundingClientRect((res) => {
						console.log('res', res)
						let top = res.height - this.scrollViewHeight;
						if (top > 0) {
							this.scrollTop = top;
						}
					}).exec()
				})
			},
			/**发送文字消息*/
			sendAdmin(problemId) {
				let _this = this;
				if (!this.content || this.content.trim() === '') {
					uni.$uv.toast("不能发送空白消息");
					return
				}
				let type = uni.getStorageSync("login-type") == 'farmer' ? 1 : 2;
				let formData = {
					"receiverId": 1, // 接收者id
					"receiverType": 3, // 接收者类型
					"content": this.content, // 发送内容
					"contentType": "1", // 发送类型：1文字 2图片-视频
					problemId,
				};
				this.$http.post(`/chat/user/send?userType=${type}`, {}, {
					data: JSON.stringify(formData)
				}).then(res => {
					if (res.code != 200) {
						uni.$uv.toast(res.msg)
						return
					}
					let msg = {
						content: _this.content,
						lastMessageTime: _this.getFormattedTime(),
					}
					this.$store.commit("message/update_customer", msg);
					_this.content = null;
					_this.getHistory();
				})
			},
			/**发送带文件的消息*/
			sendFile(contentType) {
				let contentMsg = contentType == 2 ? "图片" : "视频";
				let _this = this;
				let type = uni.getStorageSync("login-type") == 'farmer' ? 1 : 2;
				let formData = {
					"receiverId": 1, // 接收者id
					"receiverType": 3, // 接收者类型
					"filesId": _this.filesId,
					"content": " ",
					"contentType": contentType, // 发送类型：1文字 2图片-视频
				};
				this.$http.post(`/chat/user/send?userType=${type}`, {}, {
					data: JSON.stringify(formData)
				}).then(res => {
					if (res.code != 200) {
						uni.$uv.toast(res.msg)
						return
					}
					let msg = {
						content: contentMsg,
						lastMessageTime: _this.getFormattedTime(),
					}
					this.$store.commit("message/update_customer", msg);
					_this.content = null;
					_this.modalName = null;
					_this.getHistory();
				})
			},
			InputFocus(e) {
				this.InputBottom = e.detail.height
			},
			InputBlur(e) {
				this.InputBottom = 0
			},
			getWebsocket() {
				uni.$on("socketMessage", data => {
					this.getHistory()
				})
			},
			async getHistory(v) {
				await this.$http.get(`/chat/user/history/${this.theme}`).then(res => {
					if (res.data.length > 0)
						if (v == 1) {
							this.chatListHis = res.data[0].chatUserContentVOS
						} else {
							this.chatList = res.data[0].chatUserContentVOS.slice(this.chatListHis.length)
						}
					this.scrollToBottom();
					this.loadModal = false;
				})
			},
			getFormattedTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始需+1
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},

			//图片上传
			chooseImg() {
				const _this = this;
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					// sourceType: ['album'],
					success: function(res) {
						_this.uploadFilePromise(res.tempFilePaths[0]).then(function(data) {
							_this.filesId = data.data.id;
							_this.sendFile(2);
						})
					}
				});
			},
			chooseVideo() {
				let _this = this;
				uni.chooseVideo({
					// sourceType: ['album'], 
					extension: ['mov', 'mpeg', 'mp4', 'mp3'],
					success: res => {
						const fileType = res.tempFilePath.split('.').pop().toLowerCase();
						// 检查文件类型是否是允许的类型
						if (!['mov', 'mpeg', 'mp4', 'mp3'].includes(fileType)) {
							uni.showToast({
								title: '请选择 mov 或 mpeg 或 MP4 或 MP3 格式的视频',
								icon: 'none',
							});
							return;
						}
						//上传视频
						_this.uploadFilePromise(res.tempFilePath).then(function(data) {
							_this.filesId = data.data.id;
							_this.sendFile(3);
						})
						// 上传视频封面
						if (res.thumbTempFilePath) {
							uni.uploadFile({
								url: this.$hd.baseUrl + '/common/upload',
								filePath: res.thumbTempFilePath,
								name: 'file',
								header: {
									Authorization: "Bearer " + uni.getStorageSync('token'),
								},
								success: (result) => {
									console.log(result)
								}
							})
						}
					},
				});
			},

			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.$hd.baseUrl + '/common/upload',
						filePath: url,
						name: 'file',
						formData: {
							// user: 'test'
						},
						header: {
							Authorization: "Bearer " + uni.getStorageSync('token'),
						},
						success: (res) => {
							resolve(JSON.parse(res.data))
						}
					});
				})
			},


		}
	}
</script>

<style lang="scss">
	.las:last-child {
		margin-bottom: 100px;
	}

	scroll-view ::-webkit-scrollbar {
		display: none !important;
	}

	.gradient {
		display: flex;
		justify-content: center;
	}

	.gradient_radius {
		margin-top: 10px;
		width: 80%;
		height: 330px;
		border-radius: 10px;
		display: flex;
		flex-direction: column;
		align-items: center;
		align-content: center;
		justify-content: space-evenly;
	}

	.gradient_radius_text {
		font-size: clamp(24px, 8vw, 26px);
		color: #253C65;
		font-weight: bold;
		width: 100%;
		margin-left: 16%;
	}

	.gradient_radius_text_small {
		font-size: clamp(12px, 8vw, 16px);
		color: #253C65;
		margin-left: 8%;
	}

	.gradient_item {
		width: 88%;
		height: 35px;
		border-radius: 15px;
		display: flex;
		align-items: center;
		justify-content: space-around;
		font-weight: bold;
	}

	.dialog-item {
		width: 100%;
		height: 50px;
		line-height: 50px;
		text-align: center;
		border-bottom: 1px solid lightgray;
	}

	.fs {
		.gradient_radius {
			background: linear-gradient(to right, #E1EAF9, #EEEEF0);
		}

		.gradient_item {
			background-color: white;
			color: #253C65;
		}
	}

	.farmer {
		.gradient_radius {
			background: white;
		}

		.gradient_item {
			background-color: #D2FDEE;
			color: #0BCA89;
		}
	}
</style>